package com.tc.juc.pack06;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @Auther: tianchao
 * @Date: 2021/10/6 21:21
 * @Description:
 */
public class Test41 {
    public static void main(String[] args) {
        demo(()->new AtomicLong(0),(adder)->{
            adder.getAndIncrement();
        });
        demo(()->new LongAdder(), (adder)->{
            adder.increment();
        });
//        demo(()->new Integer("0"), (adder)->{
//            adder++;
//        });
    }

    /**
     *
     * @param adderSupplier  ()->{return r}
     * @param action  (r)-> {void ...}
     * @param <T>
     */
    public static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action){
        T adder = adderSupplier.get();
        List<Thread> ts = new ArrayList<>();
        // 4个线程 每人累加50w
        for (int i = 0; i < 4; i++) {
            ts.add(new Thread(()->{
                for (int j = 0; j < 500000; j++) {
                    action.accept(adder);
                }
            }));
        }
        long start = System.nanoTime();
        ts.forEach(t -> t.start());
        ts.forEach(t-> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(adder + ",cost:" + (end - start)/1000000);

    }
}
